package io.wen.scala
import scala.io.Source

/**
  * 位置信息，继承Ordered，重写比较方法
  */
case class Location(uesrId: String, locationId: String, startTime: Int, stayMinute: Int) extends Ordered[Location] {
  override def compare(that: Location): Int = {
    startTime.compareTo(that.startTime)
  }
}

object LocationStat {
  /**
    * 读取文件解析成Location列表
    */
  def readLocations(path: String): List[Location] = {
    val file = Source.fromFile(path)
    val lines = file.getLines()
    val localtionIter = lines
      .map(_.split(","))
      .map(arr => Location(arr(0), arr(1), arr(2).toInt, arr(3).toInt))

    localtionIter.toList
  }

  /**
    * 合并同一个用户的位置信息
    */
  def mergeLocation(locationList: List[Location]): List[Location] = {
    var mergedLocationList: List[Location] = List.empty

    val groupedLocations = locationList.groupBy(_.uesrId)
    for (group <- groupedLocations) {
      val sortedLocations = group._2.sorted
      val headLoc = sortedLocations.head
      val stayTotal = sortedLocations.map(_.stayMinute).sum
      val mergedLocation = Location(headLoc.uesrId, headLoc.locationId, headLoc.startTime, stayTotal)
      mergedLocationList = mergedLocation :: mergedLocationList
    }

    mergedLocationList
  }

  def main(args: Array[String]): Unit = {
    val locationList = readLocations("D:\\workspace\\project\\bd-hw\\stage6-module1-scala\\src\\locations.txt")
    val mergedLocationList = mergeLocation(locationList)
    println("merged locations ...")
    mergedLocationList.foreach(println)
  }
}

